//
//  SLNearBySearchVC.m
//  SlockApp
//
//  Created by 凯朱 on 2024/7/30.
//

#import "SLNearBySearchVC.h"
#import "SLNearHotAlertView.h"
#import <MapKit/MapKit.h>
#import "SLAnnotation.h"
#import <MapKit/MKAnnotation.h>
#import "SLMapSearchCell.h"

static  NSString *const kCellId = @"SLMapSearchCell";
@interface SLNearBySearchVC ()<CLLocationManagerDelegate,MKMapViewDelegate,UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource>{
    CLLocation *_userLocation;
    SLMapSearchModel *_clickModel;
    NSString *_address;
}
@property (nonatomic,strong) MKMapView *mapView;
@property (nonatomic,strong) CLLocationManager *locaManager;
@property (nonatomic, strong)SLAnnotation *annotion;
@property (nonatomic, strong)id lastCircle;
@property (nonatomic, strong)NSMutableArray<MKMapItem *> *searchResults;
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)SLNearHotAlertView *hotAlertView;


@end

@implementation SLNearBySearchVC

-(void)viewDidLoad{
    [super viewDidLoad];
    [self setUpSubViews];

}

-(void)setUpSubViews{
    self.isHidenNaviBar = YES;
    _tfBgView.layer.cornerRadius = 20;
    _tfBgView.layer.masksToBounds = YES;
    [_tf setPlaceholderWithPlaceholderText:kLocalString(@"Search your position") withColor:KColor_placeholdar withFont:kFont(16)];
    [_tf showCloseBtn];
    _tf.delegate = self;
    kWeakSelf(self);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self showHotAlertView];
    });
    [_tf addTarget:self action:@selector(textFieldChangeAction:) forControlEvents:UIControlEventEditingChanged];
    [_tf setCloseTextFieldTappedBlock:^{
        [weakself textFieldChangeAction:weakself.tf];
    }];
    [self addMapView];
    [self startLocation];
}

- (IBAction)cancelAction:(id)sender {
    [_tf endEditing:YES];
    [self updateSearchView:NO];
}

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    [self updateSearchView:YES];
    return YES;
}

-(void)textFieldChangeAction:(UITextField *)textField{
    
    if (textField.text.length == 0) {
        [self.searchResults removeAllObjects];
        [_tableView reloadData];
    }else{
        [self searchForPlacesWithQuery:textField.text];
    }
    
}

-(void)updateSearchView:(BOOL)isShow{
    if (isShow) {
        _cancenBtn.hidden = NO;
        _cancelBtnWidth.constant = 60;
        _tableBgView.hidden = NO;
        _hotAlertView.hidden = YES;
        
    }else{
        _tableBgView.hidden = YES;
        _cancenBtn.hidden = YES;
        _hotAlertView.hidden = NO;
        _cancelBtnWidth.constant = 0;
    }
}

-(void)showHotAlertView{
    _hotAlertView = [SLNearHotAlertView viewFromXIB];
    _hotAlertView.frame = CGRectMake(0, kScreenHeight-310, kScreenWidth, 310);
    [self.view addSubview:_hotAlertView];
    
    _hotAlertView.tag = 100;
    [_hotAlertView updateSliderValue:(int)_curRange];
    
    kWeakSelf(self);
    [_hotAlertView setBtnBlock:^(NSInteger btnIndex,id value) {
        [weakself handleHotViewAction:btnIndex value:value];
    }];
    [_hotAlertView setUpdateRangeBlock:^(NSInteger range) {
        self->_curRange = range;
        [weakself drawCircleAroundAnnotation];
    }];
}

#pragma mark -
#pragma mark - ================<保存设置>===============
-(void)handleHotViewAction:(NSInteger)index value:(id)value{
    [ZCTool showLoadingOnKeyWindow];
    _curRange = [value integerValue];
    NSDictionary *params = @{@"regionDistance":kSTRING(@(_curRange)),
                             @"dbLongitude":kSTRING(@(_regionLocation.coordinate.longitude)),
                             @"dbLatitude":kSTRING(@(_regionLocation.coordinate.latitude)),
                             @"regionAddress":_address};
    [ZKHttpManager sysncDeviceDataWith:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
        [ZCTool hideLoadingOnKeyWindow];
        if (!isSuccessed) {
            kShowToast(message);
            return;
        }
        kCurClickDevice.regionDistance = self->_curRange;
        kCurClickDevice.dbLongitude = kSTRING(@(self->_regionLocation.coordinate.longitude));
        kCurClickDevice.dbLatitude = kSTRING(@(self->_regionLocation.coordinate.latitude));
        kCurClickDevice.regionAddress = self->_address;
        [self showSuccessViews];
    }];
}

-(void)showSuccessViews{
    __weak SLSuccessAlertView *alert = [SLSuccessAlertView viewFromXIB];
    alert.contentLbl.text = kLocalString(@"Your padlock's hot area has been set successfully.");
    [alert setBtnBlock:^(NSInteger btnIndex) {
        [alert removeFromSuperview];
        [self.navigationController popViewControllerAnimated:YES];
    }];
    if (self.updateRegionBlock) {
        self.updateRegionBlock(_regionLocation,_address,_curRange);
    }
    [kAppWindow addSubview:alert];
}

-(void)addMapView{
    //创建MKMapView，设置控件视图大小
    MKMapView *mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, _mapBgView.width, _mapBgView.height)];
    //设置地图类型
    mapView.mapType = MKMapTypeStandard;
    mapView.rotateEnabled = NO; // 禁用旋转功能
    mapView.showsUserLocation = YES;
    //设置代理
    mapView.delegate = self;
    [self.mapBgView addSubview:mapView];
    [self.tableBgView addSubview:self.tableView];
    [self updateSearchView:NO];
    self.mapView = mapView;
    
    // 添加长按手势识别器
    UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
    [self.mapView addGestureRecognizer:longPressGesture];
}

#pragma mark -
#pragma mark - ================<长按地图挪动范围>===============
- (void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer {
    if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
        CGPoint touchPoint = [gestureRecognizer locationInView:self.mapView];
        CLLocationCoordinate2D coordinate = [self.mapView convertPoint:touchPoint toCoordinateFromView:self.mapView];
        _regionLocation = [[CLLocation alloc] initWithLatitude:coordinate.latitude longitude:coordinate.longitude];
        [self updateLoactionCenter:coordinate];
        [self getAddressFromCoordinate:coordinate finish:^(NSString *address) {
            self->_address = address;
        }];
    }
}

//更新region的位置
-(void)updateLoactionCenter:(CLLocationCoordinate2D)coordinate{
    // 更新标注的位置
    _annotion.coordinate = coordinate;
    
    [self.mapView removeAnnotation:_annotion];
    [self.mapView addAnnotation:_annotion];
    
    //更新圆形区域的位置
    [self drawCircleAroundAnnotation];
    //更新地图中心位置
    MKCoordinateRegion region = MKCoordinateRegionMake(coordinate, _scale);
    [self.mapView setRegion:region animated:YES];
}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    //停止获取位置信息
    [self.locaManager stopUpdatingLocation];
    _userLocation = [locations lastObject];
    //没有设置位置，默认用用户当前位置为基础点
    if (!_regionLocation) {
        _regionLocation = _userLocation;
    }
    [self addAnnotationsToMapView:_regionLocation];
    
    MKCoordinateRegion region = MKCoordinateRegionMake(_regionLocation.coordinate, _scale);
    [self.mapView setRegion:region animated:YES];
}

-(void)addAnnotationsToMapView:(CLLocation *)location{
    CLLocationCoordinate2D location1 = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude);
    //创建大头针
    SLAnnotation *annotation = [[SLAnnotation alloc] init];
    annotation.coordinate = location1;
    //添加大头针
    [self.mapView addAnnotation:annotation];
    _annotion = annotation;
    // 绘制圆形区域
    [self drawCircleAroundAnnotation];
}

-(void)drawCircleAroundAnnotation{
    if (_lastCircle) {
        [self.mapView removeOverlay:_lastCircle];
    }
    CLLocationDistance radius = _curRange;
    MKCircle *circle = [MKCircle circleWithCenterCoordinate:_annotion.coordinate radius:radius];
    [self.mapView addOverlay:circle]; // 添加圆形覆盖层
    _lastCircle = circle;
}

// 实现 MKMapViewDelegate 方法以渲染圆形
- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay {
    if ([overlay isKindOfClass:[MKCircle class]]) {
        MKCircleRenderer *circleRenderer = [[MKCircleRenderer alloc] initWithCircle:(MKCircle *)overlay];
        circleRenderer.fillColor = [KColor_O colorWithAlphaComponent:0.3]; // 填充颜色
        circleRenderer.strokeColor = KColor_O; // 边框颜色
        circleRenderer.lineWidth = 3; // 边框宽度
        return circleRenderer;
    }
    return nil;
}


-(void)startLocation{
    //初始化LocationManager
    self.locaManager = [[CLLocationManager alloc] init];
    [self.locaManager requestAlwaysAuthorization];
    //设置代理
    [_locaManager setDelegate:self];
    //设置位置的精度
    [_locaManager setDesiredAccuracy:kCLLocationAccuracyBest];
    //是指多远才更新位置信息
    [_locaManager setDistanceFilter:5.0f];
    //开始定位
    [_locaManager startUpdatingLocation];
}

//自定义大头针view
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
    //假如是定位的蓝色大头针，直接返回nil
    if ([annotation isKindOfClass:[MKUserLocation class]]) {
        return nil;
    }
    //可重用ID
    static NSString *viewID = @"myAnnotation";
    //从缓存池中取
    MKAnnotationView *annoView = [mapView dequeueReusableAnnotationViewWithIdentifier:viewID];
    //加入没有重新创建
    if(annoView == nil){
        annoView = [[MKAnnotationView alloc] init];
    }
    //赋值
    annoView.image = [UIImage imageNamed:@"icon_location"];
    //返回
    return annoView;
}

- (IBAction)backAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -
#pragma mark - ================<搜索地址>===============
-(void)searchForPlacesWithQuery:(NSString *)query {
    MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
    request.naturalLanguageQuery = query;
    MKLocalSearch *search = [[MKLocalSearch alloc] initWithRequest:request];
    [search startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error) {
        if (error) {
            NSLog(@"Search error: %@", error.localizedDescription);
            return;
        }
        NSArray *addressArray = response.mapItems;
        [self.searchResults removeAllObjects];
        for (MKMapItem *item in addressArray) {
            SLMapSearchModel *model = [SLMapSearchModel new];
            MKPlacemark *placemark = item.placemark;
            NSDictionary *dict = placemark.addressDictionary;
            NSString *distance = @"-km";
            if (self->_userLocation) {
                CLLocation *itemLocation = [[CLLocation alloc] initWithLatitude:placemark.coordinate.latitude longitude:placemark.coordinate.longitude];
                CLLocation *currentLocationObj = [[CLLocation alloc] initWithLatitude:_userLocation.coordinate.latitude longitude:_userLocation.coordinate.longitude];
                CLLocationDistance distanceInMeters = [itemLocation distanceFromLocation:currentLocationObj];
                double distanceInKilometers = distanceInMeters / 1000.0;
                distance = [NSString stringWithFormat:@"%.0fkm",distanceInKilometers];
            }
            NSString *detailAddress = kSTRING(dict[@"FormattedAddressLines"][0]);
            NSString *address = placemark.name; // 地址信息
            NSString *desc = [NSString stringWithFormat:@"%@ | %@",distance,detailAddress];
            model.address = address;
            model.detailAddress = desc;
            model.location = placemark.location;
            [self->_searchResults addObject:model];
        }
        [self->_tableView reloadData];
    }];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    SLMapSearchModel *model = _searchResults[indexPath.row];
    _clickModel = model;
    _tf.text = _clickModel.address;
    [self updateSearchView:NO];
    CLLocationCoordinate2D coordinate  = _clickModel.location.coordinate;
    _address = _clickModel.address;
    _regionLocation = [[CLLocation alloc] initWithLatitude:coordinate.latitude longitude:coordinate.longitude];
    [self updateLoactionCenter:coordinate];
}

-(void)getAddressFromCoordinate:(CLLocationCoordinate2D)coordinate finish:(void(^)(NSString *address))finish{
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    CLLocation *location = [[CLLocation alloc] initWithLatitude:coordinate.latitude longitude:coordinate.longitude];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> *placemarks, NSError *error) {
        if (error) {
            if (finish) {
                finish(@"");
            }
            NSLog(@"Error retrieving address: %@", error.localizedDescription);
            return;
        }
        if (placemarks.count > 0) {
            CLPlacemark *placemark = [placemarks firstObject];
            NSString *address = placemark.name; // 地址名称
            NSString *city = placemark.locality; // 城市
            NSString *country = placemark.country; // 国家
            if (finish) {
                finish(address);
            }
        } else {
            if (finish) {
                finish(@"");
            }
            NSLog(@"No placemarks found.");
        }
    }];
}


#pragma mark - ================<tableViewDataSource>===============
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.searchResults.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SLMapSearchCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellId];
    SLMapSearchModel *model = _searchResults[indexPath.row];
    cell.model = model;
    return cell;
}

#pragma mark - ================<UITableViewDelegate>===============
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    SLMapSearchModel *model = _searchResults[indexPath.row];
    return [SLMapSearchCell cellHeightWith:model] ;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UITableViewHeaderFooterView *headview = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"head"];
    if (!headview) {
        headview = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"head"];
        headview.frame = CGRectMake(0, 0, kScreenWidth, 0.1);
        headview.contentView.backgroundColor = KClearColor;
    }
    return headview;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UITableViewHeaderFooterView *footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"foot"];
    if (!footerView) {
        footerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"foot"];
        footerView.frame = CGRectMake(0, 0, kScreenWidth, 0.1);
        footerView.contentView.backgroundColor = KClearColor;
    }
    return footerView;
}

#pragma mark - ================<懒加载>===============
-(UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, _tableBgView.width, _tableBgView.height) style:UITableViewStyleGrouped];
        _tableView.estimatedRowHeight = 60;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerNib:[UINib nibWithNibName:kCellId bundle:nil] forCellReuseIdentifier:kCellId];
        _tableView.backgroundColor = kHexColor(@"#222224");
    }
    return _tableView;
}

-(NSMutableArray *)searchResults{
    if (!_searchResults) {
        _searchResults = [[NSMutableArray alloc] init];
    }
    return _searchResults;
}
@end
